<?php

/**
 *   OPENSHOP 
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: goods_upload.php,v 1.0 2009/10/30 08:36:58 modified $
 *   @author      winner <jsycywm@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php'); 
require(ROOT_PATH . '/includes/modules/taobao.api/cls_api.php'); 

if ($_REQUEST['act'] == 'goods_upload')
{
    /* 检查权限 */
    admin_priv();

    $smarty->assign('ur_here', '宝贝批量上传');
    $smarty->assign('cat_list', cat_list());
    $smarty->assign('brand_list',   get_brand_list());
    $smarty->assign('goods_type_list',  goods_type_list(0));
    
    $data_format_array = array(
                                'taobao'    => '上传淘宝宝贝' 
                               );
                               
	$data_format_itemcat1 = $db->getAll('select cid,name  from open_tb_itemcat where parent_cid=0') ;                           
	$data_format_itemcat2 = array(
	                        'taobao'    => '上传淘宝宝贝' 
	                       );                           
	$data_format_itemcat3 = array(
	                        'taobao'    => '上传淘宝宝贝' 
	                       ); 
    $data_tb_postage = $db->getAll("select postage_id,name from open_tb_postage where nick='".API_USER."'") ; 
	                   
    $data_format_seller_itemcat1 = $db->getAll("select cid, name,parent_cid from open_tb_sellercat where nick='".API_USER."' order by sort_order") ;     
    $arr = array(); 
    foreach ($data_format_seller_itemcat1 as $itemcat){
    	$isleaf = $db->getOne("select cid, name,parent_cid from open_tb_sellercat where nick='".API_USER."' and  parent_cid='".$itemcat['cid'] ."' order by sort_order"); 
     	if( $isleaf ) 
			$isleaf=1 ;
		else
			$isleaf=0; 
		$itemcat['isleaf'] =$isleaf ;
		$arr[] = $itemcat; 
	}
	$data_format_seller_itemcat1 = $arr;  
	$smarty->assign('data_tb_postage', $data_tb_postage);    
    $smarty->assign('data_format_seller_itemcat1', $data_format_seller_itemcat1);    
	$smarty->assign('data_format_itemcat1', $data_format_itemcat1);    
	$smarty->assign('data_format_itemcat2', $data_format_itemcat2); 
	$smarty->assign('data_format_itemcat3', $data_format_itemcat3);  
    $smarty->assign('data_format', $data_format_array); 
    assign_query_info(); 
	$smarty->display('api_tb_goods_upload.tpl');
} 
elseif ($_REQUEST['act'] == 'act_upload_taobao'){   //宝贝上传到taobao
    /* 检查权限 */ // [has_discount] => true [freight_payer] => buyer [ispostage] => true [postage_id] => 
    $GoodsParamArr = array(); //上传参数设定 
    $seller_cids= $_POST['hd_seller_cats']; ////商品所属的店铺类目列表。按逗号分隔。结构:",cid1,cid2,...,"，如果店铺类目存在二级类目，必须传入子类目cids。
	$cid = $_POST['goods_class'] ; //分类 
	$approve_status = $_POST['is_onsale'] ; //是否上架 
	$post_fee = floatval($_POST['post_express']);
    $express_fee = floatval($_POST['express']);
    $ems_fee = floatval($_POST['ems']);  
    $type = $_POST['type'] ;   
    if($type) $GoodsParamArr['type'] = $type;  
	if($seller_cids) $GoodsParamArr['seller_cids'] = $seller_cids;   //卖家自定义属性
	if($cid) $GoodsParamArr['cid'] = $cid;  //上传所属top类目
	if($approve_status ) $GoodsParamArr['approve_status'] = $approve_status ;  // approve_status  String 	 N 	 商品上传后的状态。可选值:onsale(出售中),instock(仓库中);默认值:onsale 
	if($post_fee ) $GoodsParamArr['post_fee'] = $post_fee ; 
	if($express_fee ) $GoodsParamArr['express_fee'] = $express_fee ; 
	if($ems_fee ) $GoodsParamArr['ems_fee'] = $ems_fee ; 
	
	if($_POST['has_discount'] ) $GoodsParamArr['has_discount'] = $_POST['has_discount'] ; 
	if($_POST['freight_payer'] ) $GoodsParamArr['freight_payer'] = $_POST['freight_payer'] ; 
	if($_POST['postage_id'] ) $GoodsParamArr['postage_id'] = $_POST['postage_id'] ; //卖家承担不用设置邮费和postage_id.买家承担的时候，必填邮费和postage_id

	include_once('includes/cls_phpzip.php'); 
    $where = get_export_where_sql($_POST);  
    $shop_province = '""';
    $shop_city = '""';
    if ($_CFG['shop_province'] || $_CFG['shop_city']){ 
        $sql = "SELECT region_id,  region_name FROM " . $os->table('region') . " WHERE region_id IN ('$_CFG[shop_province]',  '$_CFG[shop_city]')";
        $arr = $db->getAll($sql); 
        if ($arr){ 
            if (count($arr) == 1){ 
                if ($arr[0]['region_id'] == $_CFG['shop_province']){ 
                    $shop_province = '"' . $arr[0]['region_name'] . '"' ;
                } else{ 
                    $shop_city = '"' . $arr[0]['region_name'] . '"' ;
                }
            }else { 
                if ($arr[0]['region_id'] == $_CFG['shop_province']){ 
                    $shop_province = '"' . $arr[0]['region_name'] . '"' ;
                    $shop_city = '"' . $arr[1]['region_name'] . '"';
                }else { 
                    $shop_province = '"' . $arr[1]['region_name'] . '"' ;
                    $shop_city = '"' . $arr[0]['region_name'] . '"';
                }
            }
        }
    }
    $sql = "SELECT g.goods_id, g.goods_name,g.goods_sn, g.shop_price, g.goods_number, g.goods_desc, g.goods_img ".
    " FROM " . $os->table('goods') . " AS g ". $where; 
    
    $res = $db->query($sql); 
    
    while ($row = $db->fetchRow($res)){ 
		  UpLoadGoods( $row['goods_sn'], $GoodsParamArr );//商口代码，分类,平邮，快递，EMS  
    } 
//   echo ('上传处理完成! <a href="#" onclick="history.go(-1)">返回</a>');
}
  
/* 处理Ajax调用 */
elseif ($_REQUEST['act'] == 'get_goods_fields')
{ 
}
elseif ($_REQUEST['act'] == 'act_export_custom')
{ 
}
elseif ($_REQUEST['act'] == 'get_goods_list')
{ 
    include_once(ROOT_PATH . 'includes/cls_json.php');   
    $json = new  JSON; 
    $filters= $json->decode( $_REQUEST['JSON'] );
 
    $arr = get_goods_list($filters);
    $opt = array();  
    foreach ($arr AS $key => $val)
    {
        $opt[] = array('goods_id' => $val['goods_id'],
                        'goods_name' =>'['.$val['goods_sn'].']' . $val['goods_name']
                      );
    }
    make_json_result($opt);
}


 
/**
 *
 *
 * @access  public
 * @param
 *
 * @return string
 */
function image_path_format($content)
{
    $prefix = 'http://' . $_SERVER['SERVER_NAME'];
    $pattern = '/(background|src)=[\'|\"]((?!http:\/\/).*?)[\'|\"]/i';
    $replace = "$1='" . $prefix . "$2'";
    return preg_replace($pattern, $replace, $content);
}
  

/**
 * 生成商品导出过滤条件
 *
 * @param array $filter 过滤条件数组
 *
 * @return string
 */
function get_export_where_sql($filter)
{
    $where = '';
    if (!empty($filter['goods_ids']))
    {
        $goods_ids = explode(',', $filter['goods_ids']);
        if (is_array($goods_ids) && !empty($goods_ids))
        {
            $goods_ids = array_unique($goods_ids);
            $goods_ids = "'" . implode("','", $goods_ids) . "'";
        }
        else
        {
            $goods_ids = "'0'";
        }
        $where = " WHERE g.is_delete = 0 AND g.goods_id IN (" . $goods_ids . ") ";
    }
    else
    {
        $_filter = new StdClass();
        $_filter->cat_id = $filter['cat_id'];
        $_filter->brand_id = $filter['brand_id'];
        $_filter->keyword = $filter['keyword'];
        $where = get_where_sql($_filter);
    }
    return $where;
}

/**
 * 替换影响csv文件的字符
 *
 * @param $str string 处理字符串
 */
function replace_special_char($str, $replace = true)
{
    $str = str_replace("\r\n", "", image_path_format($str));
    $str = str_replace("\t", "    ", $str);
    $str = str_replace("\n", "", $str);
    if ($replace == true)
    {
        $str = '"' . str_replace('"', '""', $str) . '"';
    }
    return $str;
}
?>